package com.onlinelearn.courseservice.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class HomeworkGradingService {
    @Autowired
    private HomeworkRepository homeworkRepository;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private NotificationTriggerService notificationService;

    public List<HomeworkSubmission> getPendingHomeworkSubmissions(Long courseId) {
        return homeworkRepository.findPendingSubmissionsByCourseId(courseId);
    }

    public void gradeHomework(Long submissionId, GradingDTO gradingDTO) {
        HomeworkSubmission submission = homeworkRepository.findById(submissionId)
            .orElseThrow(() -> new HomeworkSubmissionNotFoundException(submissionId));

        // 检查批改是否超时
        validateGradingTimeLimit(submission);

        submission.setScore(calculateScore(gradingDTO));
        submission.setFeedback(gradingDTO.getFeedback());
        submission.setStatus(HomeworkSubmissionStatus.GRADED);

        homeworkRepository.save(submission);

        // 通知学生作业已批改
        notificationService.triggerHomeworkGradedNotification(
            submission.getStudentId(), 
            submission.getHomeworkId(), 
            submission.getScore()
        );
    }

    public String downloadHomeworkSubmissions(Long homeworkId) {
        List<HomeworkSubmission> submissions = 
            homeworkRepository.findByHomeworkId(homeworkId);

        // 批量打包下载
        return fileStorageService.createSubmissionsZipFile(submissions);
    }

    private int calculateScore(GradingDTO gradingDTO) {
        int codeQualityScore = gradingDTO.getCodeQualityScore();
        int functionalityScore = gradingDTO.getFunctionalityScore();
        return codeQualityScore + functionalityScore;
    }

    private void validateGradingTimeLimit(HomeworkSubmission submission) {
        LocalDateTime submissionTime = submission.getSubmissionTime();
        LocalDateTime now = LocalDateTime.now();
        
        if (ChronoUnit.DAYS.between(submissionTime, now) > 7) {
            throw new GradingTimeoutException("批改已超过7天时限");
        }
    }

    @Data
    public static class GradingDTO {
        private int codeQualityScore;  // 代码规范性得分
        private int functionalityScore; // 功能完成度得分
        private String feedback;
    }
} 